package com.ethink.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.db.PageUtils;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.id.generator.IdGenerator;
import com.ethink.order.api.enums.PurchaseOrderStatusEnum;
import com.ethink.order.api.enums.PurchaseReturnOrderReturnStatusEnum;
import com.ethink.order.api.enums.PurchaseReturnOrderReturnTypeEnum;
import com.ethink.order.api.info.PurchaseReturnOrderInfo;
import com.ethink.order.api.info.PurchaseReturnOrderModeInfo;
import com.ethink.order.api.model.PurchaseReturnDetailModel;
import com.ethink.order.api.model.PurchaseReturnModel;
import com.ethink.order.api.request.*;
import com.ethink.order.api.response.PurchaseReturnDetailResponse;
import com.ethink.order.common.entity.PurchaseReturnDetailOrder;
import com.ethink.order.common.entity.PurchaseReturnOrder;
import com.ethink.order.common.mapper.PurchaseReturnDetailOrderMapper;
import com.ethink.order.common.mapper.PurchaseReturnOrderMapper;
import com.ethink.order.manager.OaPayManager;
import com.ethink.order.manager.PublicManager;
import com.ethink.order.service.PurchaseReturnOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 采购退单 Service接口实现
 *
 * @author default
 * @date 2022-12-06
 */
@Slf4j
@Service
public class PurchaseReturnOrderServiceImpl implements PurchaseReturnOrderService {

    @Autowired
    private PurchaseReturnOrderMapper purchaseReturnOrderMapper;

    @Autowired
    private PurchaseReturnDetailOrderMapper purchaseReturnDetailOrderMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private PublicManager publicManager;

    @Autowired
    private OaPayManager oaPayManager;

    @Override
    public Long add(PurchaseReturnOrderAddRequest addRequest) {
        PurchaseReturnOrder purchaseReturnOrder = BeanUtil.copyProperties(addRequest, PurchaseReturnOrder.class, "item");
        String orderNo = idGenerator.cgtd();
        BigDecimal orderPrice = BigDecimal.ZERO;
        //过滤出来非0的退货数据
        List<PurchaseReturnDetailOrderAddRequest> item = addRequest.getItem().stream().filter(a -> a.getLessQty() > 0).collect(Collectors.toList());
        for (PurchaseReturnDetailOrderAddRequest detailOrderAddRequest : item) {
            PurchaseReturnDetailOrder purchaseReturnDetailOrder = BeanUtil.copyProperties(detailOrderAddRequest, PurchaseReturnDetailOrder.class);
            purchaseReturnDetailOrder.setOrderNo(orderNo);
            purchaseReturnDetailOrder.setDetailOrderNo(idGenerator.cgtdxd());
            orderPrice = orderPrice.add(publicManager.mult(new BigDecimal(detailOrderAddRequest.getLessQty()), detailOrderAddRequest.getPurchasePrice()));
            purchaseReturnDetailOrderMapper.insert(purchaseReturnDetailOrder);
        }
        purchaseReturnOrder.setOrderNo(orderNo);
        purchaseReturnOrder.setReturnAmt(orderPrice);
        purchaseReturnOrderMapper.insert(purchaseReturnOrder);
        return purchaseReturnOrder.getId();
    }

    @Override
    public Page<PurchaseReturnModel> pageQuery(PurchaseReturnPageQueryRequest request) {
        return purchaseReturnOrderMapper.pageQuery(PageUtils.buildPage(request), request);
    }

    @Override
    public PurchaseReturnDetailResponse queryDetail(Long id) {
        PurchaseReturnDetailResponse response = new PurchaseReturnDetailResponse();
        PurchaseReturnOrderInfo purchaseReturnOrderInfo = purchaseReturnOrderMapper.selectOneById(id);
        if (ObjectUtil.isEmpty(purchaseReturnOrderInfo)) {
            return response;
        }
        response.setMain(purchaseReturnOrderInfo);
        List<PurchaseReturnDetailModel> item = purchaseReturnDetailOrderMapper.selectDetailByOrderNo(purchaseReturnOrderInfo.getOrderNo());
        response.setItem(item);
        return response;
    }

    @Override
    public Boolean delete(Long id) {
        PurchaseReturnOrder purchaseReturnOrder = purchaseReturnOrderMapper.selectById(id);
        if (!PurchaseReturnOrderReturnStatusEnum.S1.getIntValue().equals(purchaseReturnOrder.getReturnStatus())) {
            throw new BusinessException(CommonRespCode.SYSTEM_ERR.getCode(), "仅支持草稿状态删除");
        }
        return purchaseReturnOrderMapper.delById(id) > 0;
    }

    @Override
    public Boolean update(PurchaseReturnOrderUpdateRequest updateRequest) {
        PurchaseReturnOrder purchaseReturnOrder = purchaseReturnOrderMapper.selectById(updateRequest.getId());
        //重新计算退款金额
        BigDecimal orderPrice = BigDecimal.ZERO;
        purchaseReturnDetailOrderMapper.delete(new LambdaQueryWrapper<PurchaseReturnDetailOrder>()
                .eq(PurchaseReturnDetailOrder::getOrderNo, purchaseReturnOrder.getOrderNo()));
        List<PurchaseReturnDetailOrderAddRequest> item = updateRequest.getItem().stream().filter(a -> a.getLessQty() > 0).collect(Collectors.toList());
        for (PurchaseReturnDetailOrderAddRequest detailOrderAddRequest : item) {
            PurchaseReturnDetailOrder purchaseReturnDetailOrder = BeanUtil.copyProperties(detailOrderAddRequest, PurchaseReturnDetailOrder.class);
            purchaseReturnDetailOrder.setOrderNo(purchaseReturnOrder.getOrderNo());
            purchaseReturnDetailOrder.setDetailOrderNo(idGenerator.cgtdxd());
            purchaseReturnDetailOrderMapper.insert(purchaseReturnDetailOrder);
            orderPrice = orderPrice.add(publicManager.mult(new BigDecimal(detailOrderAddRequest.getLessQty()), detailOrderAddRequest.getPurchasePrice()));
        }
        BeanUtil.copyProperties(updateRequest, purchaseReturnOrder, "item");
        purchaseReturnOrder.setReturnAmt(orderPrice);
        return purchaseReturnOrderMapper.updateById(purchaseReturnOrder) > 0;
    }

    @Override
    public Boolean pass(Long id) {
        PurchaseReturnOrder purchaseReturnOrder = purchaseReturnOrderMapper.selectById(id);
        if (!PurchaseReturnOrderReturnStatusEnum.S2.getIntValue().equals(purchaseReturnOrder.getReturnStatus())) {
            throw new BusinessException(CommonRespCode.SYSTEM_ERR.getCode(), "非法请求");
        }
        PurchaseReturnOrderUpdateStatusRequest request = new PurchaseReturnOrderUpdateStatusRequest();
        request.setId(id);
        if (PurchaseReturnOrderReturnTypeEnum.S1.eq(purchaseReturnOrder.getReturnType())) {
            request.setOrderStatus(PurchaseReturnOrderReturnStatusEnum.S4.getIntValue());
        } else {
            request.setOrderStatus(PurchaseReturnOrderReturnStatusEnum.S3.getIntValue());
        }
        return updateStatus(request);
    }

    @Override
    public Boolean updateStatus(PurchaseReturnOrderUpdateStatusRequest request) {
        return purchaseReturnOrderMapper.update(null, new LambdaUpdateWrapper<PurchaseReturnOrder>()
                .eq(PurchaseReturnOrder::getId, request.getId())
                .set(PurchaseReturnOrder::getReturnStatus, request.getOrderStatus())) > 0;
    }

    @Override
    public List<String> queryPurchaseReturnDetailOrderNosByOrderNos(List<String> orderNos) {
        return purchaseReturnDetailOrderMapper.queryPurchaseReturnDetailOrderNosByOrderNos(orderNos);
    }

    @Override
    public Boolean purchaseReturnOrderStatusFinish(List<String> orderNo) {
        if (CollUtil.isEmpty(orderNo)) {
            return true;
        }
        return purchaseReturnOrderMapper.update(null, new LambdaUpdateWrapper<PurchaseReturnOrder>()
                .in(PurchaseReturnOrder::getOrderNo, orderNo)
                .set(PurchaseReturnOrder::getReturnStatus, PurchaseOrderStatusEnum.S4.getIntValue())) > 0;
    }

    @Override
    public Page<PurchaseReturnOrderModeInfo> pageModeQuery(PurchaseReturnPageModeQueryRequest request) {
        return purchaseReturnOrderMapper.pageModeQuery(PageUtils.buildPage(request), request);
    }

}
